<?php
use Addons\QyWechat\Services\ProvidersApi;
use Addons\QyWechat\Services\ThirdProvider;
use Addons\QyWechat\Services\QyWechatApi;
use Addons\QyWechat\Helper;
use EasyWeChat\Factory;
$domain=$_SERVER['HTTP_HOST'];
$agency=new Model('user_agency');
$agency->find(array('domain'=>$domain));
$is_scan=$agency->is_scan;
$thirdappsetting=(new Model('qy_agency_thirdappsetting'))->find(['pid'=>$agency->id]);
$h = Helper::getInstance();
$ProvidersApi = ProvidersApi::getInstance();
$redirect_uri = urlencode($h->get_http_server_name() . '/login.html');
$qyurl="https://open.work.weixin.qq.com/wwopen/sso/3rd_qrConnect?appid=".$thirdappsetting->corpid."&redirect_uri=".$redirect_uri."&state=web_login@gyoss9&usertype=member";//admin默认管理员
if($_GET['auth_code']){
	Page::ignore_view();
	$config = [
		'corp_id'          => $thirdappsetting->corpid?$thirdappsetting->corpid:'',
		'secret'           => $thirdappsetting->providerSecret?$thirdappsetting->providerSecret:'',
		'suite_id'         => $thirdappsetting->suite_id?$thirdappsetting->suite_id:'',
		'suite_secret'     => $thirdappsetting->suite_secret?$thirdappsetting->suite_secret:'',
		'token'            => $thirdappsetting->token?$thirdappsetting->token:'',
		'aes_key'          => $thirdappsetting->encodingAESKey?$thirdappsetting->encodingAESKey:'',
		'reg_template_id'  => '',

	 ];
	 $app = Factory::openWork($config);

	 $userinfo=$app->provider->getLoginInfo($_GET['auth_code']); 
	 if($userinfo['corp_info']['corpid']){
		$corpinfo=(new Model('qy_wechat_config'))->find(['corp_id'=>$userinfo['corp_info']['corpid']]);
		if(!$corpinfo->corp_id){
		    $user = true;
		    $token = ThirdProvider::get_provider_token($thirdappsetting->corpid,$thirdappsetting->providerSecret);
		    $config_list = array_column((new Model('qy_wechat_config'))->field("corp_id")->order("id DESC")->list_all_array(),"corp_id");
            foreach ($config_list as $value){
                $body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/service/corpid_to_opencorpid?provider_access_token=".$token,
        			json_encode([
        				"corpid" => $value
        			])
        		);
        		$res = json_decode($body,1);  
        		if($res["open_corpid"] == $userinfo['corp_info']['corpid']){
        		    $corp_id = $value;
        		    break;
        		}
            }
            $corpinfo = (new Model('qy_wechat_config'))->find(['corp_id'=>$corp_id]);
		}
		if($corpinfo->corp_id){
			if($user){
		          $token = ThirdProvider::get_access_tokens($corpinfo->wid,$corpinfo->corp_id);
			      $users = array_column((new Model("qy_user_list"))->where(["wid"=>$corpinfo->wid])->field("userid")->list_all_array(),"userid");
			      $body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/batch/userid_to_openuserid?access_token=".$token,
            			json_encode([
            				"userid_list" => $users
            			])
            		);
            		$res = json_decode($body,1);
            		$open_users = $res["open_userid_list"];
            		$users_one = array_column($open_users,"userid");
            		$users_tow = array_column($open_users,"open_userid");
            		$user = $users_one[array_search($userinfo['user_info']['userid'],$users_tow)];
            		$user_inf=(new Model('qy_user_list'))->find(['wid'=>$corpinfo->wid,'userid'=>$user]);
			}else{
			    $user_inf=(new Model('qy_user_list'))->find(['wid'=>$corpinfo->wid,'userid'=>$userinfo['user_info']['userid']]);
			}
			if(!$user_inf->id){
				echo '<h3>未知员工</h3>';
				sleep(1);
				echo "<meta http-equiv='Refresh' content='1;URL=http://{$_SERVER['HTTP_HOST']}/login.html'>";
				die;
			}
			$user_i=(new Model('pubs'))->find(['id'=>$corpinfo->wid]);
			$c_uu=(new Model('user'))->find($user_i->uid);
			if($c_uu->isstop != '0'){
				echo '<h3>账号审核中或已停用,请联系管理员</h3>';
				sleep(1);
				echo "<meta http-equiv='Refresh' content='1;URL=http://{$_SERVER['HTTP_HOST']}/login.html'>";
				die;
			}else if(strtotime($c_uu->mendtime)<time()){
				echo '<h3>账号已经到期,请联系管理员升级续费</h3>';
				sleep(1);
				echo "<meta http-equiv='Refresh' content='1;URL=http://{$_SERVER['HTTP_HOST']}/login.html'>";
				die;
			}
			Session::set('r_userid',$user_inf->userid);
			set_user_login($c_uu);	
		}else{
			echo '<script>alert("该企业暂未入驻!");</script>';
			echo "<meta http-equiv='Refresh' content='1;URL=http://{$_SERVER['HTTP_HOST']}/login.html'>";
			die();
		}
	 }else{
		echo '<script>alert("授权失败!");</script>';
		echo "<meta http-equiv='Refresh' content='1;URL=http://{$_SERVER['HTTP_HOST']}/login.html'>";
		die();
	 }
	
	 
}

function parse_qq_callback($response){
	if(strpos($response, "callback") !== false){
		$lpos = strpos($response, "(");
		$rpos = strrpos($response, ")");
		$response  = substr($response, $lpos + 1, $rpos - $lpos -1);

		$msg = json_decode($response,true);

		if(isset($msg['error'])){
			Redirect::to('/main');
		}
		return $msg;
	}
	Redirect::to('/main');
}

if(Request::get('uid') && Request::get('upwd')){
	$u = new Model('user');
	$u->find(Request::get('uid'));
	if($u->has_id() && $u->pwd==Request::get('upwd')){
		set_user_login($u);
	}
}

$gkw = "DOXCX";
$gde = "DOXCX";
$gti = "DOXCX";

$u = new SampleModel();
function set_user_login($mu){
	Auth::im_user();
	Session::set('uid',$mu->id);
	Session::set('mainuid',$mu->id);
	$uid = Session::get('uid');
	if(!Session::has('level_id')){
		Session::set('level_id',$mu->level_id);
	}
	Session::set('un',$mu->un);
	Session::set('ue',$mu->email);
	Session::set('ut',$mu->telephone);
	Session::set('upc',$mu->ispwdcg);

	if($mu->isadmin=='a'){
		Auth::im_admin('admin');
	}
	Session::set('upath','/ups/'.date('Y/m',strtotime($mu->rtime)).'/'.$mu->id.'/');
	File::creat_dir(DOXCX_FRAME_PATH.DOXCX_PUB.'/'.Session::get('upath'));
	Session::set('headpic',trim($mu->headpic));
	Cookie::set('uid',$mu->id);
	$pub =(new Model("pubs"))->where(['uid'=>$mu->id])->find();
	if($pub->id)Cookie::set('wid',$pub->id);
	Cookie::set('uuid',md5($mu->un.Request::ip().$mu->pwd));
    Cookie::set('ts','1');
	Redirect::to('/start');
}


if($u->try_post()){
		$user = (new Model("user"))->find(["un"=>$u->un]);
		$mu->un = $u->un;
		if(!$user->id){
		    $token = ThirdProvider::get_provider_token($thirdappsetting->corpid,$thirdappsetting->providerSecret);
			$body = \HttpCurl::post("https://qyapi.weixin.qq.com/cgi-bin/service/corpid_to_opencorpid?provider_access_token=".$token,
    			json_encode([
    				"corpid" => $u->un
    			])
    		);
    		$res = json_decode($body,1);
    		$user = (new Model("user"))->find(["un"=>$res["open_corpid"]]);
    		if($user->id){
				$pubs = (new Model("pubs"))->find(["uid"=>$user->id]);
				$wid = $pubs->id;
				$qyConfig = (new Model('qy_wechat_config'))->find(['wid'=>$wid]);
				$ppc = (new Model('qy_providers_permanent_code'))->find(['wid'=>$wid]);
				$ppc->corpid = $u->un;
				$qyConfig->corp_id = $u->un;
				$qyConfig->save();
				$ppc->save();
    			$user->un = $u->un;
				$mu->un = $res["open_corpid"];
    			$user->save();
    		}
		}
		$mu = new Model('user');
		$mu->un = $u->un;
		$mu->pwd = md5($u->pwd);
		$mu->email = $u->un;
		$mu->telephone = $u->un;
		if(!empty($u->un) && !empty($u->pwd) && ($mu->is_real(array('un','pwd')) || $mu->is_real(array('email','pwd')) || $mu->is_real(array('telephone','pwd')))){
			if($mu->isstop != '0'){
				Page::view('login');
				tusi('账号审核中或已停用,请联系管理员');
			}else if(strtotime($mu->mendtime)<time()){
				Page::view('login');
				tusi('账号已经到期,请联系管理员升级续费');
			}else{
				if('1'== Request::post('remme')){
					//记住登录
					Cookie::set('weixinid',$mu->id);
					Cookie::set('weixinuuid',md5(Conf::$management_center_password.$mu->id));
				}
				set_user_login($mu);
			}

		}else{
			$u->pwd = '';
			Page::view('index');
			tusi('登录信息不正确');
		}
}else if(Cookie::has('weixinid')){
	$uid = Cookie::get('weixinid');
	$uuid = Cookie::get('weixinuuid');
	if($uuid==md5(Conf::$management_center_password.$uid)){
		$mu = new Model('user');
		$mu->find($uid);
		set_user_login($mu);
	}
}
if($_SERVER['IS_OEM']){
	Page::view('login');
}
//会员升级或降级操作
function user_upgrade($uid){
	$user = new Model('user');
	$user->find($uid);
	Session::remove('level_id');
	if(strtotime($user->mendtime)<time()){
		$user->level_id = 1;
		Session::set('level_id',1);
		$user->mendtime = '';
		$user->save();
	}else{
		Session::set('level_id',$user->level_id);
	}
}

//注册
$reg = new SampleModel();
$register_check=$agency->register_check;
if(Request::post('register')=='register'){
$ut= new Model('user_register');
$ut->find(1);
if($ut->has_id()){
	$registerlevel=$ut->registerlevel;
	$registerdays=$ut->registerdays;
	$registerisstop=$ut->registerisstop;
}else{
	$registerlevel=1;
	$registerdays=7;
	$registerisstop=0;
}
$domain=$_SERVER['HTTP_HOST'];
$agency=new Model('user_agency');
$agency->find(array('domain'=>$domain));
$agid=$agency->id;
$pagetype=$agency->user_pc;
$register_check=$agency->register_check;
if($reg->try_post()){
	if(!$agency->isadmin){//当前用户不是管理员
		$agencyCheck=new Model('user_agency');
		$agencyCheck->find($agency->pid);//代理商上级用户
		if($agencyCheck->isadmin && !$agency->isyg ){//如果是一级代理并且不是员工
			//当前一级代理允许开通的用户量
			$taoshu = new Model('agency_taoshu');
			$jgres = $taoshu->find($agency->level);
			$usercount=$jgres->usercount+$agency->taoshu;
			//一级代理的用户量
			$users=new Model('user');
			$counts=$users->where(array('agid'=>$agency->id))->count();
			//一级代理下级代理开通的总套数加上开通的用户量总和
			$allTaosu=totals($agency->id)+$counts;
			if($jgres->usercount!=0){//如果限制用户量的话
				if($usercount<=$allTaosu){
					//tusi('当前网站用户量已达上限');
					echo '<script type="text/javascript">alert("当前网站用户量已达上限!");</script>';
					exit;
					$taoshuCheck=1;
				}
			}
		}else if(!$agencyCheck->isadmin){//不是一级代理
			$users=new Model('user');
			$counts=$users->where(array('agid'=>$agency->id))->count();
			//代理商下级代理开通的总套数加上开通的用户量总和
			$allTaosu=totals($agency->id)+$counts;
			if($allTaosu>=$agency->taoshu){
				//tusi('当前网站用户量已达上限');
				echo '<script type="text/javascript">alert("当前网站用户量已达上限!");</script>';
				exit;
				$taoshuCheck=1;
			}
		}
   }
    $mu = new User();
    $mu->un = Request::post('telephone');
    $mu->pwd = $reg->pwd;
    $mu->email = $reg->email;
    $mu->telephone = Request::post('telephone');
	$mu->agid=$agid;
	$mu->pagetype=$pagetype; 
	//默认注册用户关闭，如果新注册用户需要审核，请把此项注释去掉(暂时不用)
    //$mu->isstop = 1;

	//获取后台设置是否审核
	$mu->isstop=$registerisstop;

	//注册用户时间
	$mu->rtime = date('Y-m-d h:i:s',time());
	//用户试用时间为1周(暂时不用)
	//$mu->mendtime = date('Y-m-d h:i:s',strtotime('+1 week'));

	//获取后台设置天数
	/**if($registerlevel!=1){
		$mu->mendtime=date('Y-m-d',time()+86400*$registerdays);
	}*/
	$mu->mendtime=date('Y-m-d',time()+86400*$registerdays);

	//获取后台设置级别
	$mu->level_id =$registerlevel;

	$yzm=Request::post('yzm');
	$code = Cache::get('sms_code');
	$telephone=Request::post('telephone');
	if($taoshuCheck!=1){
		if($register_check==1&&($yzm==null||$yzm!=$code)){
			//tusi('验证码错误');
			echo '<script type="text/javascript">alert("验证码错误!");</script>';
			exit;
		}elseif(!empty($telephone) && !empty($reg->pwd) && !$mu->is_real('un')) {
			$mu->pwd = md5($reg->pwd);
			$info = $mu->save();
			if($mu->errors()){
				foreach($mu->errors() as $item){
					$msg .= implode(',',array_values($item));
				}
			}
			$msg = $msg ?  : '注册已成功!' ;
			//tusi($msg);
			echo "<script>alert('".$msg."');</script>";
			//$info && Redirect::delay_to('/login',3);
		} elseif ($mu->is_real('un')) {
			//tusi('用户名已存在，请重新填写');
			echo '<script type="text/javascript">alert("用户名已存在，请重新填写");</script>';
			exit;
		}
	}

}
}
//查询当前代理商无限极下级代理总套数
function totals($id){
	static $all;
	$agency=new Model('user_agency');
	$aglist=$agency->where(array('pid'=>$id))->order('id')->list_all();
	foreach($aglist as $as){
		if($as->id){
			$taoshu=$as->taoshu;
			$all=$all+$taoshu;
			totals($as->id);
		}
	}
	return $all;
}
